<template>
  <div
    class="table-drag-container"
    ref="container"
    @mousedown="startDrag"
    @touchstart="startDrag"
    @mouseleave="endDrag"
    @mouseup="endDrag"
    @touchend="endDrag"
    @mousemove="onDrag"
    @touchmove="onDrag"
  >
    <div class="table-wrapper" ref="wrapper">
      <slot></slot>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const container = ref(null)
const wrapper = ref(null)

const dragState = ref({
  isDragging: false,
  startX: 0,
  scrollLeft: 0
})

let animationId = null
let velocity = 0
let lastTime = 0
let lastScrollLeft = 0

const startDrag = (e) => {
  const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.pageX

  dragState.value = {
    isDragging: true,
    startX: clientX - container.value.offsetLeft,
    scrollLeft: wrapper.value.scrollLeft
  }
  container.value.style.cursor = 'grabbing'

  // 停止惯性动画
  cancelAnimationFrame(animationId)
  velocity = 0
}

const endDrag = () => {
  if (!dragState.value.isDragging) return

  dragState.value.isDragging = false
  container.value.style.cursor = 'grab'

  // 计算速度用于惯性滑动
  const now = performance.now()
  const timeDiff = now - lastTime

  if (timeDiff > 0) {
    const scrollDiff = wrapper.value.scrollLeft - lastScrollLeft
    velocity = (scrollDiff / timeDiff) * 16

    if (Math.abs(velocity) > 1) {
      cancelAnimationFrame(animationId)
      animate()
    }
  }

  lastScrollLeft = wrapper.value.scrollLeft
  lastTime = now
}

const onDrag = (e) => {
  if (!dragState.value.isDragging) return
  e.preventDefault()

  const clientX = e.type.includes('touch') ? e.touches[0].clientX : e.pageX
  const x = clientX - container.value.offsetLeft
  const walk = (x - dragState.value.startX) * 2
  wrapper.value.scrollLeft = dragState.value.scrollLeft - walk

  // 记录最后位置用于计算速度
  lastScrollLeft = wrapper.value.scrollLeft
  lastTime = performance.now()
}

const animate = () => {
  if (Math.abs(velocity) < 0.5) {
    velocity = 0
    return
  }

  wrapper.value.scrollLeft += velocity
  velocity *= 0.95 // 摩擦系数

  animationId = requestAnimationFrame(animate)
}

onMounted(() => {
  lastScrollLeft = wrapper.value.scrollLeft
  lastTime = performance.now()

  // 添加滚轮横向滚动
  // container.value.addEventListener(
  //   'wheel',
  //   (e) => {
  //     e.preventDefault()
  //     wrapper.value.scrollLeft += e.deltaY
  //   },
  //   { passive: true }
  // )
})

onUnmounted(() => {
  cancelAnimationFrame(animationId)
})
</script>

<style lang="less" scoped>
.table-drag-container {
  width: 100%;
  overflow: hidden;
  cursor: grab;
  user-select: none;
}

.table-drag-container:active {
  cursor: grabbing;
}

.table-wrapper {
  display: inline-block;
  white-space: nowrap;
  overflow-x: auto; /* 关键！允许水平滚动 */
  width: 100%; /* 确保容器宽度足够 */
  -webkit-overflow-scrolling: touch; /* 平滑滚动(iOS) */
}
</style>
